package com.easy.web.controller.common;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.easy.common.core.R;
import com.easy.common.utils.ServletUtils;
import com.easy.merchants.pojo.dto.HouseDto;
import com.easy.merchants.service.MerchantsService;
import com.easy.user.service.IHistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.easy.common.utils.RedisConstants.*;

@RestController
@RequestMapping("/info")
@Api(tags = "房子详细信息展示控制器")
public class HouseInformationController {
    @Autowired
    private MerchantsService merchantsService;

    @CreateCache(area = "house", name = "detailed_info_", expire = 600, timeUnit = TimeUnit.SECONDS)
    private Cache<String, HouseDto> houseInfo;


    @Resource(name = "redisTemplateHouse")
    private RedisTemplate<String, Object> historyRedisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IHistoryService historyService;

    /**
     * 获取房屋信息
     *
     * @param id 房子id
     * @return {@link R}
     */
    @GetMapping
    @ApiOperation(value = "获取房屋信息")
    @ApiImplicitParam(name = "id", value = "房屋信息主键", required = true)
    public R getInfo(Long id) {
        String token = LOGIN_USER_KEY + ServletUtils.getRequest().getHeader("authorization");
        Long uid = Long.valueOf(stringRedisTemplate.opsForHash().get(token, "id") + "");

        // 从缓存获取房屋详细信息
        HouseDto houseDetailed = houseInfo.get(String.valueOf(id));
        if (houseDetailed == null) {
            houseDetailed = merchantsService.getHouseDetailed(id);
            houseInfo.put(String.valueOf(id), houseDetailed);
        }

        // 浏览历史记录
        historyService.addHistory(id, uid);

        return R.success(houseDetailed);
    }

}
